package com.chang.seckill.scheduled;

import com.chang.seckill.service.SeckillService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author: changzhenxi
 * @date: 2025年04月09日 16:52
 * @Version: 1.0
 * @description: 秒杀商品每天三点定时上架最近三天需要秒杀的商品
 */
@Service
@Slf4j
public class SeckillSkuScheduled {

    @Resource
    SeckillService seckillService;
    @Resource
    RedissonClient redissonClient;

    private final String upload_lock = "seckill:upload:lock";

    @Scheduled(cron = "0 * * * * ?")
    public void uploadSeckillSkuLatest3Days() {
        // 重复上架无需处理
        log.info("开始上架秒杀商品信息......");
        // 使用分布式锁保证幂等性
        RLock lock = redissonClient.getLock(upload_lock);
        lock.lock(10, TimeUnit.SECONDS);
        try {
            seckillService.uploadSeckillSkuLatest3Days();
        } finally {
            lock.unlock();
        }

        log.info("秒杀商品信息上架完毕......");
    }
}
